
//文件夹数据数组
const Folders = [
    {
        id:1,
        title: "20250911_090212",   //文件名
        src_rgb: "video/20250911_090212/rgb.mp4",  //可见光
        src_ir: "video/20250911_090212/ir.mp4",  //热红外
        time:"20250710152435",  //时间
        Lng:116.403875,  //经度
        Lat:39.915168,  //纬度
        hight:300,  //高度
        number:1  //异常类别号
    },
    {
        id:2,
        title: "202505102_152435",
        src_rgb: "video/03工作室.mp4",
        src_ir: "video/04工作室.mp4",
        time:"20250502152435",
        Lng:116.413875,
        Lat:39.935168,
        hight:300,
        number:2
    }
];

// let selectedPositions = [];
window.selectedPositions = [
    // {Lng: 116.40, Lat: 39.90, title: "位置A", type: "type1"},
    // {Lng: 116.41, Lat: 39.91, title: "位置B", type: "type1"}
  ];
  
  // 调用全局更新方法
  if (window.updateMapMarkers) {
    window.updateMapMarkers(window.selectedPositions);
  }

//创建文件夹
function createFolderBox(id,title,src_rgb,src_ir,time,Lng,Lat,hight,number) {
    // 获取父容器
    const container = document.querySelector('.kuang05');
    // 直接插入HTML字符串
    container.insertAdjacentHTML('beforeend', `
    <div class="kuang02" id="${id}" title="${title}" src_rgb="${src_rgb}" src_ir="${src_ir}" time="${time}" Lng="${Lng}" Lat="${Lat}" hight="${hight}" number="${number}">
        <img class="video_around video_around_chose" src="./img/folders.webp">                              
        <div class="kuang03" style="width: 100% ;height: 19%; display: inline-block">${title}</div>
    </div>
    `);
}

//创建识别结果
function createFolderResult(id,title,time,hight,number,Lng,Lat) {
    // 获取父容器
    const container = document.querySelector('.yichang-huatiao');
    // 直接插入HTML字符串
    container.insertAdjacentHTML('beforeend', `
    <div class="shibie" style=" height: auto;" id="${id}" Lng="${Lng}" Lat="${Lat}">
        <div class="scroll_top">
            <span class="scroll_title">${title}</span>
            <a class="localize"></a>
        </div>
        <div class="scroll_bottom" style=" height: auto;">                                                       
            <div class="msg_cage1" style=" height: auto;">
                <span class="localize_msg"> 时间：${time}
                    经纬度：${Lng} ，${Lat}
                    海拔: ${hight}m
                    异常类别号：${number}
                </span>
            </div>
        </div>
        <div class="location-footer" >
        </div>                                
    </div>
    `);
}



//点击播放视频
function changeVideoSource(newSrc) {
    const sourceElement = document.querySelector('.video_cage source.video');
    if (sourceElement) {
        sourceElement.src = newSrc;
        const videoElement = sourceElement.parentElement;
        videoElement.autoplay = true;
        videoElement.controls = true;
        videoElement.load(); // 重新加载视频        
    }
}

//搜索功能
function handleSearch() {
    const input = document.querySelector('.kuang04 input');
    const keyword = input.value.trim().toLowerCase();
    const videoContainers = document.querySelectorAll('.kuang05 .kuang02');
    let hasMatch = false;
    
    // 隐藏之前的无结果提示
    const noResults = document.getElementById('no-results');
    if (noResults) noResults.style.display = 'none';

    // 当搜索框为空时，显示所有视频
    if (!keyword) {
        videoContainers.forEach(container => {
            container.style.display = 'block';
        });
        // 添加：滚动回顶部恢复布局
        window.scrollTo({ top: 0, behavior: 'smooth' });
        return;
    }

    let matchCount = 0;
    let firstMatch = null; // 存储第一个匹配项用于滚动
    
    videoContainers.forEach(container => {
        const titleDiv = container.querySelector('.kuang03');
        const titleText = titleDiv ? titleDiv.textContent.toLowerCase() : '';
        
        if (titleText.includes(keyword)) {
            container.style.display = 'block';
            hasMatch = true;
            matchCount++;
            
            // 只记录第一个匹配项，不立即滚动
            if (matchCount === 1) {
                firstMatch = container;
            }
        } else {
            container.style.display = 'none';
        }
    });

    // 处理匹配结果后的滚动
    if (firstMatch) {
        // 修复：使用更精确的滚动定位
        const yOffset = -60; // 调整这个值避免顶栏遮挡
        const y = firstMatch.getBoundingClientRect().top + window.pageYOffset + yOffset;
        
        window.scrollTo({
            top: y,
            behavior: 'smooth'
        });
    }

    // 无匹配结果处理
    if (!hasMatch && noResults) {
        const keywordSpan = noResults.querySelector('.search-keyword');
        if (keywordSpan) keywordSpan.textContent = keyword;
        
        noResults.style.display = 'block';
        setTimeout(() => {
            if (noResults) noResults.style.display = 'none';
        }, 3000);
    }
}

//点击文件夹换视频
function changeFolderVideo() {
    document.querySelector('.kuang05')?.addEventListener('click', function(e) {
        // 检查点击是否来自kuang02或其内部元素
        const kuang02 = e.target.closest('.kuang02');
        if (kuang02 && this.contains(kuang02)) {
            // 获取数据
            const srcRgb = kuang02.getAttribute('src_rgb');
            const srcIr = kuang02.getAttribute('src_ir');
            //换视频
            document.querySelectorAll('.kuang02').forEach(container => {
                const video = container.querySelector('video');
                const source = container.querySelector('source');               
                if (video.title === '可见光') {
                    source.src = srcRgb;
                    video.load();
                }
                if (video.title === '热红外') {
                    source.src = srcIr;
                    video.load();
                }
            });     
        }
    });
}

//选取识别按键
function setupSelectionButton() {
    const button = document.querySelector('.custom-btn');
    if (!button) return;
    
    button.addEventListener('click', function() {
        const isSelected = this.textContent === '选取识别';
        this.textContent = isSelected ? '✔' : '选取识别';
        
        const boxes = document.querySelectorAll('.kuang05 > .kuang02');
        
        boxes.forEach(box => {
            if (isSelected) {
                box.style.border = '2px solid red';
                box.style.boxSizing = 'border-box';
                box.addEventListener('click', handleBoxClick);
            } else {
                box.style.border = '';
                box.removeEventListener('click', handleBoxClick);
            }
        });
    });
    
    function handleBoxClick(event) {
        const button = document.querySelector('.custom-btn');
        if (button && button.textContent === '✔') {
            const box = event.currentTarget;

            // 移除边框
            box.style.border = '';
    
            // 收集框的属性数据
            const id = box.getAttribute('id') || '';
            const title = box.getAttribute('title') || '';
            const time = box.getAttribute('time') || '';
            const hight = box.getAttribute('hight') || '';
            const number = box.getAttribute('number') || '';
            const Lng = parseFloat(box.getAttribute('Lng')) || 0;
            const Lat = parseFloat(box.getAttribute('Lat')) || 0;
            
            // 将数据添加到全局数组
            const positionData = {
                Lng: Lng,
                Lat: Lat,
                title: title,
                type: "type1"  // 固定类型值
            };
            
            // 确保全局数组存在
            if (!window.selectedPositions) {
                window.selectedPositions = [];
            }
            
            window.selectedPositions.push(positionData);
            
            // 调用原有功能
            createFolderResult(id, title, time, hight, number, Lng, Lat);
            
            // 更新地图标记
            if (window.updateMapMarkers) {
                window.updateMapMarkers(window.selectedPositions);
            } else {
                console.warn("地图更新函数不可用，请确保地图已初始化");
            }
            
            // 移除该框的点击事件监听器
            box.removeEventListener('click', handleBoxClick);
        }
    }
}

//发布异常键
const collectedTitles = [];

function SendButton() {
    const button = document.querySelector('.left-custom-btn');
    if (!button) return;
    
    button.addEventListener('click', function() {
        const isSelected = this.textContent === '发布异常';
        this.textContent = isSelected ? '✔' : '发布异常';
        
        const boxes = document.querySelectorAll('.kuang05 > .kuang02');
        
        // 进入选择模式：添加边框和事件
        if (isSelected) {
            boxes.forEach(box => {
                box.style.border = '2px solid orange';
                box.style.boxSizing = 'border-box';
                box.addEventListener('click', handleBoxClick);
            });
        } 
        // 退出选择模式：提交数据并重置
        else {
            boxes.forEach(box => {
                box.style.border = '';
                box.removeEventListener('click', handleBoxClick);
            });
            
            // 提交收集的标题并清空数组
            if (collectedTitles.length > 0) {
                post_Result(collectedTitles);
                collectedTitles.length = 0; // 清空数组
            }
        }
    });
    
    function handleBoxClick(event) {
        const button = document.querySelector('.left-custom-btn');
        if (button && button.textContent === '✔') {
            const box = event.currentTarget;
            box.style.border = '';
            
            const item = {
                time: box.getAttribute('time') || '',
                Lng: box.getAttribute('Lng') || '',
                Lat: box.getAttribute('Lat') || '',
                hight: box.getAttribute('hight') || '',
                number: box.getAttribute('number') || ''
            };           
            // 将对象添加到数组中
            collectedTitles.push(item);
            
            box.removeEventListener('click', handleBoxClick);
        }
    }
}


//识别结果刷新键
function UpdateButton(){
    document.addEventListener('DOMContentLoaded', function() {
        // 获取按钮和识别内容容器
        const clearButton = document.querySelector('.right-btn');
        const resultContainer = document.querySelector('.yichang-huatiao');
        
        // 添加点击事件监听器
        clearButton.addEventListener('click', function() {
            // 清空识别内容
            resultContainer.innerHTML = '';
            
            // 确保使用全局变量
            if (typeof window.selectedPositions === 'undefined') {
                window.selectedPositions = [];
            } else {
                // 清空全局位置数组
                window.selectedPositions.length = 0;
            }
            
            // 更新地图标记（清空所有标记）
            if (typeof window.updateMapMarkers === 'function') {
                window.updateMapMarkers(window.selectedPositions);
            } else {
                console.warn("地图更新函数不可用，无法清空地图标记");
            }
        });
    });
}

//文件夹刷新键
function RefreshButton(){
    document.querySelector('.top-right-btn').addEventListener('click', function() {
        document.querySelector('.kuang05').innerHTML = '';
        //获取视频
        getAllVideos();
        //获取txt文本
        get_recordsData();
        if (allVideos && allVideos.length > 0 && recordsData && recordsData.length > 0) {
            for(let i=1; i <= Folders.length; i++){      
                createFolderBox(allVideos[i].page,recordsData[i].id,allVideos[i].src01,allVideos[i].src02,recordsData[i].time,recordsData[i].Lng,recordsData[i].Lat,recordsData[i].hight,recordsData[i].number);
            }  
        }
        else{
            console.warn("获取文件夹失败");
        }
    });
}

// function get(ULT){
//     axios({
//         method:'GET',
//         url: ULT,
//     }).then(response => {
//         searchResults = response;
//     })
// };

